package com.wenlin.myproduction.base;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.wenlin.myproduction.MyApplication;
import com.wenlin.myproduction.R;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.SystemUtil;
import com.wenlin.myproduction.util.TypeData;
import com.wenlin.myproduction.util.UI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author 文琳
 * @time 2018/3/2 17:45
 * @desc 弹窗母类
 */
public abstract class BaseDialogFragment extends DialogFragment {
    protected int tryTimes = 3;
    private Unbinder unbinder;
    private FragmentManager fm;

    @Override
    public void onStart() {
        super.onStart();
        if (!Checker.notNull(getDialog())) {
            return;
        }
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params;
        if (window != null) {
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params = window.getAttributes();
            params.gravity = Gravity.CENTER;
            params.width = SystemUtil.getWindowWidthAndHeight(MyApplication.getMyApplicationContext())[0] * 75 / 100;
            window.setAttributes(params);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        if (Checker.notNull(getDialog()))
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.NormalDialog);
        View rootView = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        initView(rootView, savedInstanceState);
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Checker.notNull(unbinder)) {
            unbinder.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 获取Fragment
     *
     * @param activity 上下文
     * @return 所求
     */
    protected Fragment getFragment(Activity activity, String tag) {
        getFm(activity);
        Fragment fragment;
        //移除旧的弹窗
        if (Checker.notNull(fm)) {
            fragment = fm.findFragmentByTag(tag);
            if (Checker.notNull(fragment)) {
                FragmentTransaction ft = fm.beginTransaction();
                ft.remove(fragment);
                ft.commitAllowingStateLoss();
                fm.executePendingTransactions();
            }
        }
        //新增弹窗
        fragment = Fragment.instantiate(activity, tag);
        return fragment;
    }

    /**
     * 获取FragmentManager
     *
     * @param activity 上下文
     */
    private void getFragmentManager(Activity activity) {
        if (Checker.notNull(activity)) {
            if (activity instanceof BaseSwipeActivity) {
                fm = ((BaseSwipeActivity) activity).getSupportFragmentManager();
            } else if (activity instanceof BaseActivity) {
                fm = ((BaseActivity) activity).getSupportFragmentManager();
            } else if (activity instanceof AppCompatActivity) {//MainActivity就是
                fm = ((AppCompatActivity) activity).getSupportFragmentManager();
            }
        }
    }

    /**
     * 获取FragmentManager
     *
     * @param activity 上下文
     * @return 所求
     */
    protected FragmentManager getFm(Activity activity) {
        if (Checker.isNull(fm)) getFragmentManager(activity);
        return fm;
    }

    /**
     * 获取是否能够显示
     *
     * @param activity 上下文
     * @return 所求
     */
    protected boolean getShow(Activity activity) {
        return getShow(activity, true);
    }

    /**
     * 获取是否能够显示
     *
     * @param activity      上下文
     * @param onlyOneDialog 是否只能显示一个同种弹窗
     * @return 所求
     */
    protected boolean getShow(Activity activity, boolean onlyOneDialog) {
        boolean show = false;
        if (Checker.notNull(activity)) {
            if (activity instanceof BaseActivity) {
                BaseActivity theActivity = (BaseActivity) activity;
                if (!theActivity.isFinishing() && theActivity.isStateEnable())
                    show = true;
            }
        }
        //如果发现弹窗已存在并且正在显示，则不再重新显示弹窗
        Dialog dialog = getDialog();
        if (Checker.notNull(dialog) && dialog.isShowing())
            show = false;
//        if (show && onlyOneDialog) {//如果前面判断可以显示了，需要再判断一下如下参数是否满足，此处是为了防止弹窗短期内连弹多次
//            long timeAllow = SpUtil.getSpUidTempDeleteWhenClearCache().getLong(UserManage.getInstance().getUid() + ValSp.SHOW_DIALOG_FRAGMENT_TIME_ALLOW);
//            long timeNow = System.currentTimeMillis();
//            if (timeNow < timeAllow) show = false;
//            else
//                SpUtil.getSpUidTempDeleteWhenClearCache().put(UserManage.getInstance().getUid() + ValSp.SHOW_DIALOG_FRAGMENT_TIME_ALLOW, timeNow + 300);//同种弹窗必须隔0.3秒之后才能弹出
//        }
        return show;
    }

//    /**
//     * 解决 Can not perform this action after onSaveInstanceState问题
//     *
//     */
//    public void showAllowingLoss(Activity activity) {
//        try {
//            Class cls = DialogFragment.class;
//            Field mDismissed = cls.getDeclaredField("mDismissed");
//            mDismissed.setAccessible(true);
//            mDismissed.set(this, false);
//            Field mShownByMe = cls.getDeclaredField("mShownByMe");
//            mShownByMe.setAccessible(true);
//            mShownByMe.set(this, true);
//        } catch (Exception e) {
//            //调系统的show()方法
//            show(getFm(activity), tag);
//            return;
//        }
//        FragmentTransaction ft = fm.beginTransaction();
//        ft.add(this, tag);
//        ft.commitAllowingStateLoss();
//    }
//
//    @Override
//    public void dismiss() {
//        //防止横竖屏切换时 getFragmentManager置空引起的问题：
//        //Attempt to invoke virtual method 'android.app.FragmentTransaction
//        //android.app.FragmentManager.beginTransaction()' on a null object reference
//        if (getFragmentManager() == null) return;
//        super.dismissAllowingStateLoss();
//    }

    //因为在此类中已经注册了EventBus所以这里需要空的threadHandler
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void threadHandle(TypeData typeData) {
    }

    public void setTitle(String title) {
        if (Checker.notNull(getActivity())) {
            TextView tv = getActivity().findViewById(R.id.tv_title);
            UI.setText(tv, title);
            ImageView iv = getActivity().findViewById(R.id.iv_close);
            UI.setOnClickListener(iv, v -> hide());
        }
    }

    /**
     * 关闭弹窗
     */
    public void hide() {
        try {
            //Dialog必须在所在Activity销毁之前销毁,否则会报：android.view.WindowLeaked异常。
//            if (Checker.isNull(getActivity()) || getActivity().isFinishing()) {
//                return;
//            }
//            if (isAdded())
            dismissAllowingStateLoss();//这个方法是DialogFragment里面的方法，方法里有dialog.dismiss方法。所以下方的代码可以直接注释掉
            //没初始化就会出现问题
//            Dialog dialog = getDialog();
//            if (Checker.notNull(dialog) && dialog.isShowing()) {
//                dialog.dismiss();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView(View view, Bundle savedInstanceState);
}
